﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Dapper_Core.Basic;
using Dapper_Core.Common;
using Dapper_Core.Model;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using UEditor.Core;

namespace Dapper_Core.Web.Controllers
{
    [TypeFilter(typeof(IgnoreCheckSessionFilter))]
    public class UEditorController : Controller
    {
        private readonly UEditorService _ueditorService;
        public UEditorController(UEditorService ueditorService)
        {
            this._ueditorService = ueditorService;
        }

        //如果是API，可以按MVC的方式特别指定一下API的URI
        [HttpGet, HttpPost]
        public ContentResult Upload()
        {
            var response = _ueditorService.UploadAndGetResponse(HttpContext);
            //将图片url改为绝对路径时，ueditor.json中的图片路径前缀也要随之修改
            response.Result = RemedyUrl(response.Result);
            return Content(response.Result, response.ContentType);
        }

        private string RemedyUrl(string result)
        {
            try
            {
                UEditorResult uEditorResult = JsonConvert.DeserializeObject<UEditorResult>(result);
                if(Appsettings.UEditorFileServer.EndsWith("/") && !uEditorResult.url.IsEmpty() && uEditorResult.url.StartsWith("/"))
                {
                    uEditorResult.url = Appsettings.UEditorFileServer.TrimEnd('/') + uEditorResult.url;
                }
                else if(!Appsettings.UEditorFileServer.EndsWith("/") && !uEditorResult.url.IsEmpty() && !uEditorResult.url.StartsWith("/"))
                {
                    uEditorResult.url = Appsettings.UEditorFileServer + "/" + uEditorResult.url;
                }
                else
                {
                    uEditorResult.url = Appsettings.UEditorFileServer + uEditorResult.url;
                }
                return JsonConvert.SerializeObject(uEditorResult);
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(MethodBase.GetCurrentMethod().DeclaringType.FullName, "改进UEditor资源链接异常", "result=" + result, ex, "DapperCore");
                return result;
            }
        }
    }

    public class UEditorResult
    {
        public string state { get; set; }
        public string url { get; set; }
        public string title { get; set; }
        public string original { get; set; }
    }
}